import { _decorator, Component, instantiate, Node, Prefab, UITransform } from 'cc';
import { Card } from './Card';
import { Seat } from './Seat';
import { CardTemplate } from './CardTemplate';
import { Player } from './Player';
const { ccclass, property } = _decorator;

@ccclass('InitCards')
export class InitCards extends Component {


    @property([Card])
    cards: Card[] = []
    @property(Prefab)
    cardPrefab: Prefab | null = null;

    @property(Prefab)
    playerPrefab: Prefab | null = null;
    @property([Player])
    players: Player[] = []

    cardNodes: Node[] = []
    seats: Array<Node> = []
    catchCardStackIndex: number; // 抓取牌堆对象的 索引 
    catchCardIndex: number; // 从牌堆抓牌的索引
    catchFlowerCardStackIndex: number; // 补花抓取牌堆对象的 索引 
    catchFlowerCardIndex: number;// 补花牌堆抓牌的索引 索引 
    onLoad() {
        this.generateSeats()
        this.init()



    }

    start() {
        // 

    }
    // 生成麻将
    init() {
        let id = 0;
        const types: Array<String> = ['wan', 'tong', 'tiao', 'feng', 'zhongfabai', 'hongheihua']
        const cards: Array<Card> = []
        for (let j = 0; j < 3; j++) {
            for (let index = 0; index < 9; index++) {
                for (let i = 0; i < 4; i++) {
                    cards.push(new Card(id, types[j], index + 1));
                    id++;
                }
            }
        }
        for (let index = 0; index < 4; index++) {
            for (let i = 0; i < 4; i++) {
                cards.push(new Card(id, types[3], index + 1));
                id++;
            }
        }
        for (let index = 0; index < 3; index++) {
            for (let i = 0; i < 4; i++) {
                cards.push(new Card(id, types[4], index + 1));
                id++;
            }
        }
        for (let index = 0; index < 8; index++) {
            cards.push(new Card(id, types[5], index + 1));
            id++;
        }

        // 暂时不洗牌
        // this.cards = this.shuffleArray(cards)

        this.cards = cards
        // this.cards
        for (let index = 0; index < this.cards.length; index++) {

            const item = instantiate(this.cardPrefab);
            const data = this.cards[index];

            this.cardNodes.push(item)
            item.getComponent(CardTemplate).init(data);
        }
        this.splitArray(this.cardNodes)

    }
    // 洗牌  打乱顺序
    shuffleArray(array: Array<Card>) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }
    // 分配牌堆
    splitArray(arr) {
        var result = [];
        const temArr = [...arr]
        for (var i = 0; i < temArr.length; i += 36) {
            var chunk = temArr.slice(i, i + 36);

            result.push(chunk);
        }
        for (let index = 0; index < this.seats.length; index++) {
            const seat = this.seats[index];
            const seatComp = seat.getComponent(Seat)

            seatComp.initStackCardNode(result[index], index);
        }


    }

    // 生成座位
    generateSeats() {
        this.seats = this.node.children.slice(0, 4)

    }
    /**
     * 
     * @param index ; 开始抓牌的人
     * @param count; 一次性抓牌的数量
     * @returns 
     */

    RoundStartDraw(index: number, count: number) {
        return new Promise<void>((resolve) => {
            setTimeout(() => {
                const seat: Node = this.seats[index];
                for (let i = 0; i < count; i++) {
                    const startStack = this.seats[this.catchCardStackIndex].getChildByName("stack")
                    const node = [...startStack.children][this.catchCardIndex]
                    const cardTemplate: CardTemplate = node.getComponent(CardTemplate)
                    console.log(cardTemplate.id);

                    cardTemplate.state = 1
                    switch (index) {
                        case 0:
                            cardTemplate.direction = 'self'
                            break;
                        case 1:
                            cardTemplate.direction = 'after'
                            break;
                        case 2:
                            cardTemplate.direction = 'face'
                            break;
                        case 3:
                            cardTemplate.direction = 'font'
                            break;
                    }
                    seat.getComponent(Seat).grabHandCard(node)
                    const newNode = new Node("");
                    const ui = node.getComponent(UITransform)
                    newNode.addComponent(UITransform);
                    newNode.getComponent(UITransform).width = ui.width
                    newNode.getComponent(UITransform).height = ui.height
                    startStack.insertChild(newNode, this.catchCardIndex)
                    this.catchCardIndex--;
                    if (this.catchCardIndex == -1) {
                        this.catchCardIndex = 35
                        this.catchCardStackIndex = (this.catchCardStackIndex + 3) % 4
                        if (this.catchCardStackIndex == 4) {
                            this.catchCardStackIndex = 0
                        }
                    }

                }
                resolve()
            }, 500)
        })

    }



    // 开始抓牌
    async startDraw(sieves: number[]) {
        sieves = [4, 1]
        //
        const sum = sieves[0] + sieves[1] - 1

        this.catchFlowerCardStackIndex = sum % 4;
        this.catchFlowerCardIndex = 35 - Math.min(sieves[0], sieves[1]) * 2;
        this.catchCardIndex = 35 - Math.min(sieves[0], sieves[1]) * 2
        this.catchCardStackIndex = sum % 4;
        let startDrawSeatIndex = 0;



        for (let i = 0; i < 17; i++) {
            const count = i < 12 ? 4 : 1
            await this.RoundStartDraw(startDrawSeatIndex, count);
            startDrawSeatIndex++;
            if (startDrawSeatIndex > 3) startDrawSeatIndex = 0;
        }



        // // //  手牌排序
        for (let i = 0; i < 4; i++) {
            const hand = this.seats[i].getChildByName("hand")
            const action = this.seats[i].getChildByName("action")
            // 复制 数据排序
            const arr = [...hand.children]

            arr.sort((a, b) => {

                return a.getComponent(CardTemplate).id - b.getComponent(CardTemplate).id
            })
            //
            let hua = []  // 筛选 [花]
            // 重置索引
            for (let index = 0; index < arr.length; index++) {
                const node = arr[index];
                if (node.getComponent(CardTemplate).id > 123) {
                    hua.push(node)
                }
                node.setSiblingIndex(index)
            }

            for (let index = 0; index < hua.length; index++) {
                const node = hua[index];
                node.setParent(action)
                node.getComponent(CardTemplate).state = 3

                node.getComponent(CardTemplate).updateCardSpriteFrame()
            }



        }


        // // // 第一个人开始行动
        const node = this.seats[0].getComponent(Seat)
        node.roundAction()


    }
    /**
     * 
     * @param i 0 self 1 after 2 face 3 font
     * @param startStack  抓取谁的牌堆
     * @param index 抓取牌的索引
     */
    grad(i: number, startStack: Node, index: number) {
        const seat: Node = this.seats[i]
        const node = [...startStack.children][index]
        const cardTemplate: CardTemplate = node.getComponent(CardTemplate)


        cardTemplate.state = 1
        switch (i) {
            case 0:
                cardTemplate.direction = 'self'
                break;
            case 1:
                cardTemplate.direction = 'after'
                break;
            case 2:
                cardTemplate.direction = 'face'
                break;
            case 3:
                cardTemplate.direction = 'font'
                break;
        }
        seat.getComponent(Seat).grabHandCard(node)
        const newNode = new Node("");
        const ui = node.getComponent(UITransform)
        newNode.addComponent(UITransform);
        newNode.getComponent(UITransform).width = ui.width
        newNode.getComponent(UITransform).height = ui.height

        startStack.insertChild(newNode, index)


    }


    update(deltaTime: number) {

    }
}


